﻿using HandyControl.Expression.Shapes;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
using System.Security.AccessControl;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using VCLib.Network.HTTPServers;
using VCLib.Util;
using VideoCarousel.Entity;

namespace VideoCarousel.Control
{
    public delegate void IPAddressChanged(IPAddress[] localAddress);
   
    internal class AppControl:System.ComponentModel.INotifyPropertyChanged
    {
        public string rootPath { get; set; }
        private string playInfoMsg;
        public static AppControl appControl { get; set; }

        public List<ListDir> ListDirs { get; set; }
        public UserCommand UserCommand { get; set; }

        public System.Timers.Timer updateListDirTimer;
        public System.Timers.Timer updatePlayStateTimer;
        private string appType = "";
        public mediaInfo mediaInfo { set; get; }
        public string PlayInfoMsg
        {
            set { playInfoMsg = value; PropertyChanged?.Invoke(this,new PropertyChangedEventArgs("PlayInfoMsg")); }
            get { return playInfoMsg; }
        }    
        private int volume =0;
        public int Volume
        {
            set { 
                volume = value; 
                PropertyChanged?.Invoke(this,new PropertyChangedEventArgs("Volume")); 
                PlayCtr.SetVolume(value); 
            }
            get { return volume; }
        }
        private AppControl()
        {
         
            appType = VCLib.Util.ConfigHelp.ReadConfig("appType");
            this.rootPath = VCLib.Util.ConfigHelp.ReadConfig("videoFolder");
            ListDirs = new List<ListDir>();
            updateListDirTimer = new System.Timers.Timer(2000);
            updateListDirTimer.Elapsed += (s,e)=> {
                UpdateFile();
            };
            updatePlayStateTimer = new System.Timers.Timer(500);
            updatePlayStateTimer.Elapsed += (s, e) => {
                UpdatePlayState();
            };
      
            UserCommand = new UserCommand();
            UserCommand.UserCommandExecute += UserCommand_UserCommandExecute;
        }

    

        public void UpdateFile()
        {
            var rootList = new List<ListDir>();
            var root = new DirectoryInfo(rootPath);
            ListDir rootDir = new ListDir() { Name = "根目录", FullName = rootPath };
            var list = new List<ListFile>();
            foreach (var file in root.GetFiles())
            {
                if (IsAdd(file.FullName))
                    list.Add(new ListFile { FullName = file.FullName, Name = file.Name , ListDirName = rootDir.Name });
            }
            rootDir.ListFile = list;
            rootList.Add(rootDir);

            foreach (var item in root.GetDirectories())
            {
                ListDir tempDir = new ListDir() { Name = item.Name, FullName = item.FullName, ListFile = new List<ListFile>() };

                foreach (var file in item.GetFiles())
                {
                    if (IsAdd(file.FullName))
                    {
                        tempDir.ListFile.Add(new ListFile { FullName = file.FullName, Name = file.Name,ListDirName= item.Name });

                    }
                }

                rootList.Add(tempDir);
            }
            ListDirs = rootList;
        }
        public bool IsAdd(string fullName)
        {
            if(appType== "audio")
            {
                return IsAudio(fullName);
            }
            else
            {
                return IsVideo(fullName) || IsImage(fullName) || IsAudio(fullName);
            }
        }
        public bool IsVideo(string item)
        {
            string extension = System.IO.Path.GetExtension(item);
            if (extension == ".mp4" || extension == ".mov" || extension == ".avi"
                 || extension == ".rmvb" || extension == ".flv" || extension == ".3gp"
                  || extension == ".mpeg" || extension == ".mpg4" || extension == ".wmva")
                return true;
            return false;
        }
        public bool IsImage(string item)
        {
            string extension = System.IO.Path.GetExtension(item);
            if (extension == ".bmp" || extension == ".jpg" || extension == ".png"
                 || extension == ".tif")
                return true;
            return false;
        }
        public bool IsAudio(string item)
        {
            string extension = System.IO.Path.GetExtension(item);
            if (extension == ".mp3" || extension == ".wav" || extension == ".aiff"
               )
                return true;
            return false;
        }
        public static AppControl Instance
        {
            get
            {
                if (appControl == null) { appControl = new AppControl(); }
                return appControl;
            }
        }
        private int httpPort = 80;
        public HttpInput HttpInput;
        IPAddress[] LocalIpAddress;
        public void Init()
        {
            mediaInfo = mediaInfo.Get();
            PlayStateInfo = PlayStateInfo.GetPlayStateInfo();

            this.httpPort = VCLib.Util.ConfigHelp.ReadConfig<int>("httpPort");
            UpdateFile();
            LocalIpAddress = VCLib.Util.IPHelp.GetLocalIp();
            HttpInput = new HttpInput(LocalIpAddress, httpPort);
            try
            {
                HttpInput.Init();
                LogHelp.Debug("Http初始化成功");
                Timer = new System.Timers.Timer(2 * 1000);
                Timer.Elapsed += Timer_Elapsed;
                Timer.Start();
            }
            catch (Exception ex)
            {
                LogHelp.Write("Http初始化失败", ex);
            }
            updateListDirTimer.Start();
            updatePlayStateTimer.Start();
            Volume = PlayStateInfo.Vol;

            if (VCLib.Util.ConfigHelp.ReadConfig<bool>("autoPlay"))
            {
                Task.Run(() => {
                    System.Threading.Thread.Sleep(10*1000);
                    UserCommand_UserCommandExecute("播放");
                });
            }
        }
        System.Timers.Timer Timer { set; get; }
        int ipChangedNum = 0;
        public event IPAddressChanged IPAddressChanged;
        public event PropertyChangedEventHandler PropertyChanged;

        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            Timer.Enabled = false;
            try
            {
                var temp = VCLib.Util.IPHelp.GetLocalIp();
                var changed = !IPAddressContains(LocalIpAddress, temp);
                if (changed)
                {
                    ipChangedNum++;
                    if (ipChangedNum > 3)
                    {
                        ipChangedNum = 0;
                        LocalIpAddress = temp;
                        IPAddressChanged?.Invoke(temp);
                        string ips = "";
                        for (int i = 0; i < temp.Length; i++)
                        {
                            ips += temp[i] + " ";
                        }
                        LogHelp.Write($"IPAddressChanged:" + ips);

                    }
                }
                else
                {
                    ipChangedNum = 0;
                }

            }
            catch (Exception ex)
            {
                LogHelp.Debug($"IPChanged:{ex.Message}");

            }
            finally
            {
                Timer.Enabled = true;
            }





        }
        public static bool IPAddressContains(IPAddress[] a, IPAddress[] b)
        {
            if (a == b) return true;
            if (a.Length != b.Length) return false;
            for (int i = 0; i < a.Length; i++)
            {
                if (a[i].ToString() != b[i].ToString())
                {
                    return false;
                }
            }
            return true;
        }



        public void NextPlay()
        {
            if (string.IsNullOrEmpty(AppControl.Instance.PlayStateInfo.FullName))
            {
                //播放第一个
                if (AppControl.Instance.ListDirs[0].ListFile.Count > 0)
                {
                    var name = AppControl.Instance.ListDirs[0].ListFile[0].FullName;
                    if (System.IO.File.Exists(name))
                    {
                        AppControl.Instance.PlayCtr.Play(name);
                    }
                }
            }
            else
            {
                var path = System.IO.Path.GetDirectoryName(AppControl.Instance.PlayStateInfo.FullName);
                foreach (var item in AppControl.Instance.ListDirs)
                {
                    if (item.FullName == path)
                    {

                        for (var i = 0; i < item.ListFile.Count; i++)
                        {
                            if (AppControl.Instance.PlayStateInfo.FullName == item.ListFile[i].FullName)
                            {
                                if ((i + 1) >= item.ListFile.Count)
                                {
                                    AppControl.Instance.PlayCtr.Play(item.ListFile[0].FullName);
                                }
                                else
                                {
                                    AppControl.Instance.PlayCtr.Play(item.ListFile[i + 1].FullName);
                                }
                                break;
                            }
                        }
                        break;
                    }
                }
            }
        }
        public void RandowPlay()
        {
            if (string.IsNullOrEmpty(AppControl.Instance.PlayStateInfo.FullName))
            {
                //播放第一个
                if (AppControl.Instance.ListDirs[0].ListFile.Count > 0)
                {
                    var name = AppControl.Instance.ListDirs[0].ListFile[0].FullName;
                    if (System.IO.File.Exists(name))
                    {
                        AppControl.Instance.PlayCtr.Play(name);
                    }
                }
            }
            else
            {
                var path = System.IO.Path.GetDirectoryName(AppControl.Instance.PlayStateInfo.FullName);
                foreach (var item in AppControl.Instance.ListDirs)
                {
                    if (item.FullName == path)
                    {
                      var index =  Random.Next(0, item.ListFile.Count);
                        AppControl.Instance.PlayCtr.Play(item.ListFile[index].FullName);
                        break;
                    }
                }
            }
        }
        private Random Random = new Random();
        public PlayStateInfo PlayStateInfo { get; set; } 

        public IPlayCtr PlayCtr { get; set; }
        public void PlayFileNameUpdate(string fileName)
        {
           PlayStateInfo.PlayState = 1;
            PlayStateInfo.FullName = fileName;
            var dir = System.IO.Path.GetDirectoryName(fileName);
            if (dir == rootPath || dir == null)
            {
                PlayStateInfo.DirName = "根目录";
            }
            else
            {
                PlayStateInfo.DirName =new System.IO.DirectoryInfo(dir).Name;

            }
            PlayStateInfo.Name = System.IO.Path.GetFileName(fileName);
            PlayStateInfo.Current = 0;
        }
        public void UpdatePlayState()
        {
            PlayCtr.UpdatePlaySate();
            string str = "停止";
            if (PlayStateInfo.PlayState == 1)
            {
                str = "正在播放";
            }
            else if (PlayStateInfo.PlayState == 1)
            {
                str = "暂停";
            }
            PlayInfoMsg = $"{str} {TimeSpan.FromSeconds(PlayStateInfo.Current).ToString(@"hh\:mm\:ss")} / {TimeSpan.FromSeconds(PlayStateInfo.Count).ToString(@"hh\:mm\:ss")} {PlayStateInfo.Name}";
        }
        private void UserCommand_UserCommandExecute(object parameter)
        {
            string str=  parameter.ToString();
            if (str == "播放")
            {
                if (string.IsNullOrEmpty(PlayStateInfo.FullName))
                {
                    if (ListDirs[0].ListFile.Count > 0)
                    {
                        PlayCtr.Play(ListDirs[0].ListFile[0].FullName);
                    }
                   
                }
                else
                {
                    PlayCtr.Play();
                }
               
            }
            else if (str == "暂停")
            {
                PlayCtr.Pause();
            }
            else if (str == "停止")
            {
                PlayCtr.Stop();
            }
            else if (str == "上一首")
            {
                if (string.IsNullOrEmpty(AppControl.Instance.PlayStateInfo.FullName))
                {
                    //播放第一个
                    if (AppControl.Instance.ListDirs[0].ListFile.Count > 0)
                    {
                        var name = AppControl.Instance.ListDirs[0].ListFile[0].FullName;
                        if (System.IO.File.Exists(name))
                        {
                            AppControl.Instance.PlayCtr.Play(name);
                        }
                       
                    }
                }
                else
                {
                    var path = System.IO.Path.GetDirectoryName(AppControl.Instance.PlayStateInfo.FullName);
                    foreach (var item in AppControl.Instance.ListDirs)
                    {
                        if (item.FullName == path)
                        {
                            for (var i = 0; i < item.ListFile.Count; i++)
                            {
                                if (AppControl.Instance.PlayStateInfo.FullName == item.ListFile[i].FullName)
                                {

                                    if ((i - 1) < 0)
                                    {
                                        AppControl.Instance.PlayCtr.Play(item.ListFile[item.ListFile.Count - 1].FullName);

                                    }
                                    else
                                    {
                                        AppControl.Instance.PlayCtr.Play(item.ListFile[i - 1].FullName);
                                    }
                                    break;
                                }
                            }
                            break;
                        }
                    }
                }
            }
            else if (str == "下一首")
            {
                NextPlay();
            }
        }
        ~AppControl() 
        {
            updatePlayStateTimer.Dispose();
            updateListDirTimer.Dispose();
        }
    }
}